{% extends 'base/userinfo.html' %}


{% block head %}
<meta charset="utf-8">
<title>salt部署 管理界面</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="/asset/layui/css/layui.css" media="all">
<link rel="stylesheet" href="/asset/css/global.css" media="all">
<script src="/asset/js/js-yaml.min.js"></script>
<script src="/asset/js/util.js" charset="utf-8"></script>

<style>
    .layui-body {
        left: 30px !important;
    }

    .e {
        height: 600px;
        min-width: 1000px;
        font-size: 14px;
    }

    .type_btns {
        margin-top: 10px;
    }

    label {
        word-wrap: break-word;
    }

    .layui-form-label {
        width: 170px !important;

    }

    .btn_right {
        float: right;
        margin-right: 30px;
    }

    #test_deploy_btn {
        margin-left: 50px;
    }

    #deploy_btn {
        margin-left: 150px;

    }

    #tag_select {
        display: block;
        width: 50%;
        height: 20px;
        padding: 6px 12px;
        font-size: 14px;
        line-height: 1.428571429;
        color: #555;
        vertical-align: middle;
        background-color: #fff;
        border: 1px solid #ccc;
        border-radius: 4px;
        -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
        box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
        -webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
        transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
    }
</style>


{% endblock %}

{% block body %}


<div id="box_preview" style="display: none">

    <form class="layui-form" action="" id="form_preview">

        <div class="layui-form-item">
            <label class="layui-form-label" style="font-size: 20px;color: red;background-color: #F2F2F2"
                   id="deploy_btn_label"></label>

            <div class="layui-input-block">
                <button class="layui-btn layui-btn-normal" id="test_deploy_btn">测试部署</button>
                <button class="layui-btn layui-btn-danger" id="deploy_btn">正式部署</button>

                <button class="layui-btn layui-btn-warm layui-btn-sm btn_right" id="rollback">版本回退</button>

            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label">部署输出:</label>

            <div class="layui-input-block">
                <div class="e" id="editor_preview"></div>
                <script src="/asset/js/ace.js" type="text/javascript"
                        charset="utf-8"></script>

                <script>
                    var editor_preview = ace.edit("editor_preview");
                    editor_preview.setTheme("ace/theme/monokai");
                    editor_preview.getSession().setMode("ace/mode/yaml");

                    editor_preview.container.style.lineHeight = 2
                    editor_preview.container.style.fontSize = "14px"
                    editor_preview.renderer.updateFontSize()
                </script>

            </div>

        </div>


        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn layui-btn-primary" id="pre">上一次</button>

                <button class="layui-btn layui-btn-normal layui-btn-disabled" disabled id="next">下一次</button>

            </div>
        </div>

    </form>

</div>

<div class="layui-body">

    <div class="layui-tab layui-tab-brief">
        <ul class="layui-tab-title">
            <li class="layui-this"><a href="salt-run.html">线上部署</a></li>


            {% if permission.prod %}

            <li><a href="salt-run-config.html">salt部署配置</a></li>
            {% endif %}

        </ul>
        <div class="layui-tab-content"></div>
    </div>

    <h1 class="site-h1">salt线上部署 </h1>

    <div class="type_btns" id="tags">
        <a href="salt-run.html?tag=全部" class="layui-btn layui-btn-primary layui-btn-sm" id="host">全部</a>

    </div>

    <table class="layui-hide" id="LAY_table_user" lay-filter="demo"></table>

</div>


<script type="text/html" id="salt_run_btns">

    {{# var deploys = d.execmd }}
    {{# var app_name = d.app_name }}

    {{#  for( var t in deploys){ }}

    <button class="layui-btn layui-btn-sm " id="btn_salt_run_cmd{{ deploys[t][0] }}_{{ app_name }}"
            lay-event="btn_salt_run_cmd{{ deploys[t][0] }}">
        {{ deploys[t][0] }}
    </button>
    {{#  } }}

</script>


<script type="text/html" id="salt_run_btns_misc">

    {{# var deploys = d.misc }}
    {{# var app_name = d.app_name }}

    {{#  for( var t in deploys){ }}

    <button class="layui-btn layui-btn-sm " id="btn_salt_run_misc{{ deploys[t][0] }}_{{ app_name }}"
            lay-event="btn_salt_run_misc{{ deploys[t][0] }}">
        {{ deploys[t][0] }}
    </button>
    {{#  } }}

</script>


<script src="/asset/layui/layui.js" charset="utf-8"></script>
<script>
    layui.use(['table', "form", "laytpl", "element"], function () {
        done = []
        var laytpl = layui.laytpl

        var element = layui.element;

        $ = layui.$

        var table = layui.table;

        //方法级渲染
        table.render({
            elem: '#LAY_table_user'
            , url: '/config_list?tag=' + getUrlParamValue("tag")
            , cols: [[

                {field: 'app_name', sort: true, fixed: true, width: 200, title: "应用名称"},
                {field: 'remark', width: 400, title: "应用描述"},

                {
                    fixed: 'right',
                    align: 'center',
                    width: 1000,
                    field: "execmd",
                    toolbar: '#salt_run_btns',
                    title: "部署操作"
                },
                {
                    fixed: 'right',
                    align: 'center',
                    field: "misc",
                    toolbar: '#salt_run_btns_misc',
                    title: "其他配置"
                },


            ]]
            , id: 'testReload'
            , page: true,
            limit: 20,
            limits: [20, 50, 100],

        });

        //监听表格复选框选择
        table.on('checkbox(demo)', function (obj) {
            console.log(obj)
        });


        var current_deploy = ""
        //监听工具条
        table.on('tool(demo)', function (obj) {

                if (obj.event === 'del') {
                    layer.confirm("确认删除配置", {
                        btn: ['确认', '取消']
                        , btn3: function (index, layero) {

                        }
                    }, function (index, layero) {

                    }, function (index) {

                    })
                } else if (obj.event.indexOf('btn_salt_run_cmd') >= 0) {
                    current_deploy = obj.event + "_" + obj.data.app_name
                    show_salt_run_modal(obj.data, obj.event.substr("btn_salt_run_cmd".length), "execmd")
                    var _html = $("#" + current_deploy).parent().html()
                    var pos = _html.indexOf(current_deploy) - 6
                    _html = _html.substr(0, pos) + " layui-btn-primary " + _html.substr(pos)
                    var u = {}
                    u[deploy_type_var] = _html
                    obj.update(u);
                } else if (obj.event.indexOf('btn_salt_run_misc') >= 0) {
                    current_deploy = obj.event + "_" + obj.data.app_name
                    show_salt_run_modal(obj.data, obj.event.substr("btn_salt_run_misc".length), "misc")
                    var _html = $("#" + current_deploy).parent().html()
                    var pos = _html.indexOf(current_deploy) - 6
                    _html = _html.substr(0, pos) + " layui-btn-primary " + _html.substr(pos)
                    var u = {}
                    u[deploy_type_var] = _html
                    obj.update(u);
                }
            }
        );

        var last_time = ""

        function get_title(app_name, last_time) {
            return '测试部署: ' + '<span style="color: red">' + app_name + '</span>' + "&nbsp;&nbsp;&nbsp;&nbsp;上次执行时间: &nbsp;&nbsp;" +
                '<span style="font-size: 18px;color: red"> ' + new Date(last_time * 1000).format("yyyy-mm-dd hh:ii:ss") + '  </span>';
        }


        var deploy_name_var = ""
        var app_name_var = ""
        var deploy_type_var = ""

        function show_salt_run_modal(data, deploy_name, deploy_type) {
            deploy_name_var = deploy_name
            app_name_var = data.app_name
            deploy_type_var = deploy_type


            $.ajax({
                url: "/salt_ssh/salt-run-history?is_test=0&app_name=" + app_name_var + "&deploy_name=" + deploy_name_var + "&deploy_type=" + deploy_type_var,
                type: "GET",
                success: function (_data) {
                    console.log(_data)
                    editor_preview.setValue(_data['data']['rs'] || "")
                    last_time = _data['data']['ctime'] || 0
                    var title_txt = get_title(deploy_name_var, last_time)

                    index = layer.open({
                        type: 1,
                        title: title_txt,              // [可选]
                        content: $('#box_preview'),          // 对话框中的内容部分
                        area: ['1300px', "850px"],    // 对话框的大小 [可选]
                        shadeClose: true,           // 为 true 时点击遮罩关闭 [可选]
                    });
                    $("#deploy_btn_label").html(deploy_name)

                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })

            console.log(data)
        }

        var form = layui.form

        form.verify({
            yaml: function (value) {
                data = JSON.parse(value)
                if (data == null) {
                    return 'json 不合法';
                }
                return false
            }

        });


        function ssh_exc(app_name, deploy_name, version, test) {
//            $("#" + current_deploy).addClass("layui-btn-primary")

            var index = layer.load(0, {
                shade: [0.8, '#585858'] //0.1透明度的白色背景
            });
            $.ajax({
                url: "/salt_ssh/salt-run?is_test=" + test + "&app_name=" + app_name + "&deploy_name=" + deploy_name + "&version=" + version + "&deploy_type=" + deploy_type_var,
                type: "GET",
                success: function (_data) {
                    console.log(_data)
                    editor_preview.setValue(_data)
                    layer.close(index)
                },
                error: function (xhr, type) {
                    layer.alert('页面提示: 失败! 请刷新页面!', {
                        skin: 'layui-layer-lan'
                        , closeBtn: 0
                        , anim: 0 //动画类型
                    });
                }
            })

        }

        $("body").find("#deploy_btn").on('click', function (event) {
            event.preventDefault()
            layer.confirm("确认执行??", {
                btn: ['确认', '取消']
                , btn3: function (index, layero) {

                }
            }, function (index, layero) {
                layer.close(index)
                ssh_exc(app_name_var, deploy_name_var, "", 0)
                var timestamp = Math.round(new Date().getTime() / 1000);
                $(".layui-layer-title").html(get_title(app_name_var, timestamp))

                skip = 0
                $("#next").attr("disabled", true)
                $("#next").addClass("layui-btn-disabled")

            }, function (index) {

            })

        })


        $("body").find("#test_deploy_btn").on('click', function (event) {
            event.preventDefault()

            ssh_exc(app_name_var, deploy_name_var, "", 1)
            var timestamp = Math.round(new Date().getTime() / 1000);
            $(".layui-layer-title").html(get_title(app_name_var, timestamp))

            skip = 0
            $("#next").attr("disabled", true)
            $("#next").addClass("layui-btn-disabled")

        })

        $("body").find("#rollback").on('click', function (event) {
            event.preventDefault()
            layer.prompt({title: '请输入回退工程版本号!!', formType: 0}, function (version, index) {
                var version_nums = version.split(".")
                var version_num = version_nums[version_nums.length - 1]
                if (parseInt(version_num) <= 0) {
                    lay.message("回退版本号不对!")
                    return
                }

                layer.close(index);
                ssh_exc(app_name_var, deploy_name_var, version, 0)
                var timestamp = Math.round(new Date().getTime() / 1000);
                $(".layui-layer-title").html(get_title(app_name_var, timestamp))

                skip = 0
                $("#next").attr("disabled", true)
                $("#next").addClass("layui-btn-disabled")

            });
        })

        var skip = 0

        $("body").find("#next").on('click', function (event) {

            event.preventDefault()
            var disabled = $("#next").attr("disabled")
            if (disabled) {
                return
            }

            skip = skip - 1
            if (skip <= 0) {
                $("#next").attr("disabled", true)
                $("#next").addClass("layui-btn-disabled")

            }

            $.ajax({
                url: "/salt_ssh/salt-run-history?is_test=0&app_name=" + app_name_var + "&deploy_name=" + deploy_name_var + "&skip=" + skip + "&deploy_type=" + deploy_type_var,
                type: "GET",
                success: function (_data) {
                    console.log(_data)
                    editor_preview.setValue(_data['data']['rs'] || "")
                    setTimeout(function () {
                        editor_preview.gotoLine(1)
                    }, 100)

                    last_time = _data['data']['ctime'] || 0

                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })

        })

        $("body").find("#pre").on('click', function (event) {

            event.preventDefault()
            skip = skip + 1
            if (skip > 0) {
                $("#next").attr("disabled", false)
                $("#next").removeClass("layui-btn-disabled")
            }

            $.ajax({
                url: "/salt_ssh/salt-run-history?is_test=0&app_name=" + app_name_var + "&deploy_name=" + deploy_name_var + "&skip=" + skip + "&deploy_type=" + deploy_type_var,
                type: "GET",
                success: function (_data) {
                    console.log(_data)
                    editor_preview.setValue(_data['data']['rs'] || "")

                    setTimeout(function () {
                        editor_preview.gotoLine(1)
                    }, 500)

                    last_time = _data['data']['ctime'] || 0

                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })

        })


        function init_summary() {
            $.ajax({
                url: "/tag",
                type: "GET",
                data: "",
                success: function (_data) {
                    if ((typeof _data) == "string") {
                        _data = JSON.parse(_data)
                    }
                    console.log(_data)

                    var _option = ""

                    var _html = ['<a href="salt-run.html?tag=全部" class="layui-btn layui-btn-primary layui-btn-sm ' + ("全部" == getUrlParamValue("tag") ? "layui-btn-warm" : "") + ' " id="host">全部</a>\n']
                    for (var ii in _data.data.tagList) {
                        var tag = _data.data.tagList[ii]

                        _html.push('<a href="salt-run.html?tag=' + tag + '" class="layui-btn layui-btn-primary layui-btn-sm ' + (tag == getUrlParamValue("tag") ? "layui-btn-warm" : "") + ' " id="host">' + tag + '</a>\n')
                        _option += '<option value="' + tag + '">' + tag + '</option>'
                    }
                    $("#tags").html(_html)

                },
                error: function (xhr, type) {
                    layer.msg("请求失败");
                }
            })
        }

        init_summary()


    });


    Date.prototype.format = function (fmt) { //author: meizz
        var o = {
            "m+": this.getMonth() + 1,                 //月份
            "d+": this.getDate(),                    //日
            "h+": this.getHours(),                   //小时
            "i+": this.getMinutes(),                 //分
            "s+": this.getSeconds(),                 //秒
            "q+": Math.floor((this.getMonth() + 3) / 3), //季度
            "S": this.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }
</script>
{% endblock %}
